<!--
 * @Description: 租户管理-首页 
 * @Author: 马山
 * @Date: 2020-03-30 15:36:26
 * @LastEditTime: 2020-03-30 12:43:55
 * @LastEditors: 马山
 -->

<template>
    <div class="tenantOperation">
        <div class="tenantOperation-content">
            <!-- 条件选择组件 -->
            <query-form :queryList="queryList" @submit="submit"></query-form>
            <!-- 增删改查按钮组 -->
            <div class="operate-content">
                <el-button @click="create" type="primary" size="mini">
                    <app-icon iconName="vcloud-btn-add"></app-icon>
                    新建订单
                </el-button>
                <el-button @click="revice" plain size="mini" :disabled="openServiceBtn">
                    <app-icon iconName="vcloud-xiugai"></app-icon>
                    修改
                </el-button>
                <el-button @click="reviceOrderCode" plain size="mini" :disabled="openServiceBtn">
                    <app-icon iconName="vcloud-xiugai"></app-icon>
                    修改订单号
                </el-button>
                <!-- <el-button @click="remove" plain size="mini">
                    <app-icon iconName="vcloud-shanchu"></app-icon>
                    删除
                </el-button> -->
            </div>
            <!-- 表格数据 -->
            <div class="tenant-operation-table disabledCheckbox">
                <el-table
                    ref="singleTable"
                    :height="tableHeight()"
                    :data="tableData"
                    :row-class-name="setRowClassName"
                    header-row-class-name="header-row"
                    @selection-change="getCurrentRow"
                    @select=" ( selection , row ) => selectRowProduct(row)"
                    @row-click="selectRowProduct"
                    style="width: 100%">

                    <el-table-column
                    type="selection"
                    width="55">
                    </el-table-column>

                    <!-- 渲染表头 -->
                    <el-table-column
                        v-for='col in tableHeadData'
                        :width="columnWidth(col)"
                        :fixed="col.title=='operation' ? 'right':false"
                        :show-overflow-tooltip=" true "
                        :prop="col.title"
                        :label="col.text"
                        :key="col.title">
                        <!-- 自定义显示格式 -->
                        <template slot-scope="scope">
                            <!-- 服务状态 -->
                            <div v-if="col.title == 'serviceStatus' ">
                                <p v-if="scope.row[col.title]=='1'||scope.row[col.title]=='null'">未开通</p>
                                <p v-if="scope.row[col.title]=='2'">开通</p>
                            </div>
                            <!-- 服务名称详情 -->
                            <div v-else-if="col.title == 'productInfo' ">
                                <div v-if="scope.row[col.title]">
                                    <p>{{ scope.row[col.title].registerNumber + "," + scope.row[col.title].lifeTime}}</p>
                                    <p>{{ scope.row[col.title].spaceCapacity + "," + scope.row[col.title].products}}</p>
                                    <p>{{ scope.row[col.title].beginDate + "至" + scope.row[col.title].expireDate}}</p>
                                </div>
                            </div>
                            <!-- 订单类型 -->
                            <div v-else-if="col.title == 'orderType' ">
                                <p v-if="scope.row[col.title] == '1' ">正式</p>
                                <p v-if="scope.row[col.title] == '2' ">试用</p>
                            </div>
                            <!-- 操作 -->
                            <div v-else-if="col.title == 'operation' ">
                                <div class="viewDetail" @click="openDetail(scope.$index, scope.row)">订单详情</div>
                                <div :class="['viewDetail',{disabled:scope.row.serviceStatus=='2'}]" @click="configService(scope.$index, scope.row)">配置订单服务</div>
                                <div :class="['viewDetail',{disabled:scope.row.serviceStatus=='2'}]" @click="openService(scope.$index, scope.row)">确认服务开通</div>
                            </div>
                            <span v-else>
                                <!-- <i class="el-icon-time"></i> -->
                                <span>{{ scope.row[col.title] }}</span>
                            </span>
                        </template>
                    </el-table-column>

                </el-table>
            </div>

            <!-- 分页插件 -->
            <div v-if="paginationShow">
                <el-pagination
                    @size-change="handleSizeChange"
                    @current-change="pageHandleCurrentChange"
                    @prev-click="prevClick"
                    @next-click="nextClick"
                    :current-page="1"
                    :page-sizes="pageSizes"
                    :page-size="pageSize"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="total">
                </el-pagination>
            </div>
            
            <!-- 添加或修改订单弹出框 -->
            <div><ModifyDialog ref="modifyDialog" @submit="modifyCallback"></ModifyDialog></div>
            <!-- 配置订单服务弹出框 -->
            <div><ConfigDialog ref="configDialog" @submit="submitConfig"></ConfigDialog></div>
            <!-- 修改某条数据的弹出框 -->
            <div><ModifyItemDialog ref="modifyItemDialog" @submit="submitItemConfig"></ModifyItemDialog></div>
        </div>
    </div>
</template>

<script>
import QueryForm from "@/components/query.vue";
import ModifyDialog from "./components/modifyDialog.vue"; //添加或修改订单弹出框
import AppStatus from "@/components/AppCommon/AppStatus";
import ConfigDialog from "./components/configDialog.vue";
import ModifyItemDialog from "./components/modifyItemDialog.vue";
import {totalPageSize, totalPageSizes} from "../../utils/tool"; //配置订单服务弹出框
export default {
    name: "tenant-page",
    components: {
        QueryForm,
        AppStatus,
        ModifyDialog,
        ConfigDialog,
        ModifyItemDialog
    },
    computed: {},
    data: () => ({
        // 条件选择组数据
        queryList:[
            {
                type:"text",
                title:"单位名称",
                value:"",
                key:"unitName"
            },{
                type:"text",
                title:"单位产品名称", //--------新增
                value:"",
                key:"unitProductName"
            },{
                type:"number",
                title:"订单编号",
                value:"",
                key:"orderSn"
            },{
                type:"select",
                title:"订单类型",
                value:"",
                key:"orderType",
                options:[
                    {value:"",label:"全部"},
                    {value:"1",label:"正式"},
                    {value:"2",label:"试用"}
                ]
            },{
                type:"date",
                title:"订单时间",
                value:"", //["2020-10-04","2020-10-09"]
                key:"orderTime",
                group:true
            }
        ],
        // 表头列数据
        tableHeadData:[

            {  //订单类-----
                title:"orderTime",
                text:"订单时间"
            },{
                title:"orderSn",
                text:"订单编号"
            },{
                title:"orderType",
                text:"订单类型"
            },

            { //租户类-----
                title:"unitName",
                text:"单位名称"
            },{
                title:"unitProductName",
                text:"单位产品名称"
            },

            // {
            //     title:"unitProductCode",
            //     text:"单位产品编号"
            // },{ //产品类-----
            //     title:"productName",
            //     text:"产品名称"
            // },{
            //     title:"productCode",
            //     text:"产品编号"
            // },
            
            { //结果---
                title:"serviceStatus",
                text:"服务结果"
            },{
                title:"operation", 
                text:"操作"
            }
        ],
        
        queryCondition:{ //查询条件记录
            unitName:"", //单位名称
            unitProductName:"",//单位产品名称
            // productName:"", //产品名称
            // productCode:"", //产品编号
            orderTime:"", //订单时间
            orderSn:"", //订单编号
            saleType:"", //订单类型
        },
        tableData:[], //表格所有行数据
        currentRow:"", //选择的当前行的数据
        markRowSelect:{},//记录表格单选
        openServiceBtn:false,//记录下当前数据是否已开通服务
        // 分页插件----
        paginationShow:true,
        pageSizes:totalPageSizes, //下拉动态设置当前页数
        pageSize:totalPageSize,    //当前页显示多少条数据 默认10条
        pageNum:1, //当前页
        total:0, //总条目数
        
    }),
    created() {
        
    },
    mounted() { //页面初始化
        this.getTenantData();
    },
    watch: {},
    methods: {

        //监听查询条件回调
        submit(data){
            console.log(data);
            data.forEach( item =>{ //设置查询条件
                switch(item.key){
                    case "unitName" : //单位名称
                        this.queryCondition.unitName = item.value;
                        break;
                    case "unitProductName" : //单位产品名称
                        this.queryCondition.unitProductName = item.value;
                        break;
                    // case "productName" : //产品名称
                    //     this.queryCondition.productName = item.value;
                    //     break;
                    // case "productCode" : //产品编号
                    //     this.queryCondition.productCode = item.value;
                    //     break;
                    case "orderTime" : //订单时间
                        this.queryCondition.orderTime = item.value;
                        break;
                    case "orderSn" : //订单编号
                        this.queryCondition.orderSn = item.value;
                        break;
                    case "orderType" : //订单类型
                        this.queryCondition.saleType = item.value;
                        break;
                }
            });
            this.pageNum = 1;
            this.getTenantData();
            this.paginationShow = false;
            this.$nextTick( () =>{
                this.paginationShow = true;
            });
        },
        
        // 添加订单
        create(){
            let data = {
                isCreate:"create",
                unitData:{
                    //单位名称，单位ID，租户编号，单位产品名称
                    unitName:"",
                    unitId:"",
                    unitProductName:"",
                    //订单编号，订单类型，下单时间
                    orderSn:"",
                    orderType:"1",
                    orderTime:"",
                },
                title:"添加产品服务"
            }
            this.$refs.modifyDialog.open(data);
        },
        //修改
        revice(){
            let currentRow = this.currentRow;
            if(!this.checkRowData())return;
            console.log(currentRow);
            if(currentRow.serviceStatus == "1"){
                this.$message("服务已开通,无需修改!");
                return;
            }
            let data = {
                isCreate:"modify",
                unitData:currentRow,
                title:"修改产品服务"
            };
            this.$refs.modifyDialog.open(data);
        },
        //修改订单号
        reviceOrderCode(){
            if(!this.checkRowData())return;
            let options = {
                data:this.currentRow.orderSn, //订单号
                title:"修改订单号",
                label:"订单号："
            }
            this.$refs.modifyItemDialog.open(options);
        },
        //删除
        remove(){
            if(!this.checkRowData())return;
            this.api.unitServiceListDelete({
                orderSn:this.currentRow.orderSn, //订单编号
                unitProductCode:this.currentRow.unitProductCode //单位产品编号
            }).then( res =>{
                console.log(res);
            }).catch( err =>{
                console.log(err);
            });
        },
        modifyCallback(){//监听新建修改回调
            this.getTenantData();
        },
        //监听修改订单号回调
        submitItemConfig(data){
            this.currentRow.orderSn = data;
        },
        // 获取表格数据
        getTenantData(){
            this.api.getTenantUserService(
                {
                    pageNum:this.pageNum,
                    pageSize:this.pageSize,
                    ...this.queryCondition
                },{loading:true}
            ).then(res =>{
                console.log(res);
                let data = res.data;
                if(!data){
                    this.tableData = []; //以防接口如果突然挂了,结果还显示的原来的数据
                    return;
                }
                let listData = data.records;
                if(!listData || listData.length==0){
                    this.tableData = [];
                    return;
                }
                this.total = data.totalCount;
                let dataArray = [];
                listData.forEach( item =>{
                    let obj = {
                        unitName:item.unitName, //单位名称
                        unitProductName:item.unitProductName,//单位产品名称
                        unitOrgCode:item.unitOrgCode,//单位产品码
                        // productName:item.productName, //产品名称
                        // productCode:item.productCode, //产品编号
                        orderTime:this.formatTime(item.orderTime), //订单时间
                        orderTimeTemp:item.orderTime,//时间戳
                        orderSn:item.orderSn, //订单编号
                        orderType:item.orderType, //订单类型
                        serviceStatus:item.serviceStatus, //服务结果
                        unitProductCode:item.unitProductCode, //单位产品编号---额外数据
                        unitId:item.unitId, //单位ID---额外数据
                        operation:"操作"
                    };
                    dataArray.push(obj);
                });
                this.tableData = dataArray;
            }).catch(err =>{
                console.log(err);
            });
        },
        // 订单详情
        openDetail(index, row){
            let data = {
                isCreate:"detail",
                unitData:row,
                title:"订单详情"
            };
            this.$refs.modifyDialog.open(data);
        },
        //配置订单服务按钮
        configService(index,row){
            if(row.serviceStatus =='2')return;
            let data = {
                isCreate:"config",
                unitData:row
            };
            // this.$refs.modifyDialog.open(data);
            this.$refs.configDialog.open(data);
        },
        submitConfig(){ //监听配置订单设置回调
            this.getTenantData();
        },
        //确认服务开通按钮
        openService(index, row){
            // if(row.serviceStatus =="2"){
            //     this.$message("服务已开通,无需再次开通!");
            //     return;
            // }
            if(row.serviceStatus =='2')return;
            this.api.openService({
                orderSn:row.orderSn,
                serviceStatus:"2"
            }).then(res =>{
                console.log(res);
                this.$message("服务开通成功!");
                row.serviceStatus = '2'; //2:开通成功
                this.$refs.singleTable.clearSelection();
            }).catch( err =>{
                console.log(err);
                // this.$message("服务开通失败!");
            });
        },


        // 表格处理------------------------
        // 单选
        selectRowProduct(row) {
            this.$refs.singleTable.clearSelection();
            if ( this.markRowSelect && this.markRowSelect.orderSn === row.orderSn ) {
                this.markRowSelect = {};
                this.$refs.singleTable.setCurrentRow();
            } else {
                this.markRowSelect = row;
                this.$refs.singleTable.setCurrentRow(row);
                this.$refs.singleTable.toggleRowSelection(row);
                this.openServiceBtn = row.serviceStatus=="2" ? true : false;
            }
        },
        // 选中变化
        getCurrentRow(row) {
            this.currentRow = row[0];
        },
        //设置行class
        setRowClassName({row, column, rowIndex, columnIndex}){
            row.currentIndex = rowIndex; //手动给每个行设置一个索引
        },

        
        // 分页插件-----------------
        handleSizeChange(val) { //pageSize 改变时会触发
            console.log(`每页 ${val} 条`);
            this.pageSize = val;
            this.pageNum = 1;
            this.getTenantData();
            this.paginationShow = false;
            this.$nextTick( () =>{
                this.paginationShow = true;
            });
        },
        pageHandleCurrentChange(val) { //pageNum 改变时会触发
            console.log(`当前页: ${val}`);
            this.pageNum = val;
            this.getTenantData();
        },
        prevClick(val){  //用户点击上一页按钮改变当前页后触发
            console.log(`上一页: ${val}`);
            this.pageNum = val;
            this.getTenantData();
        },
        nextClick(val){ //用户点击下一页按钮改变当前页后触发
            console.log(`下一页: ${val}`);
            this.pageNum = val;
            this.getTenantData(); 
        },
        // 校验是否选择了数据
        checkRowData(del){
            let currentRow = this.currentRow;
            if(!currentRow || currentRow.length == 0 ){
                this.$message("未选择任何数据！");
                return false;
            }
            if(!del && currentRow.length > 1){
                this.$message("只能选择一条数据！");
                return false;
            }
            return true;
        },

        //动态设置下表格高度
        tableHeight(){
            let windowH = document.body.offsetHeight;
            let height = windowH - 290;
            return height;
        },
        //手动设置一下列宽
        columnWidth(col){
            let mainContentW = document.body.offsetWidth - 200;
            let width = 50;
            switch (col.title){
                case "unitName":
                    width = mainContentW / 6;
                    break;
                case "unitProductName":
                    width = mainContentW / 7;
                    break;
                // case "unitId":
                //     width = mainContentW / 9;
                //     break;
                // case "tenantType":
                //     width = mainContentW / 18;
                //     break;
                // case "productName":
                //     width = mainContentW / 9;
                //     break;
                // case "productCode":
                //     width = mainContentW / 9;
                //     break;
                
                case "orderTime":
                    width = mainContentW / 7;
                    break;
                case "orderSn":
                    width = mainContentW / 7;
                    break;
                case "orderType":
                    width = mainContentW / 15;
                    break;
                case "serviceStatus":
                    width = mainContentW / 15;
                    break;
                case "operation":
                    width = mainContentW / 9;
                    break;
                default:
                    width = '100%'
                    break;
            }
            return width;
        },
        formatNumber (n){
            n = n.toString()
            return n[1] ? n : '0' + n
        },
        // 时间格式化
        formatTime(date){
            if(!date)return;
            date = new Date(JSON.parse(date));
            let year = date.getFullYear()
            let month = date.getMonth() + 1
            let day = date.getDate()
            let hour = date.getHours()
            let minute = date.getMinutes()
            let second = date.getSeconds();
            return [year, month, day].map(this.formatNumber).join('-') + ' ' + [hour, minute, second].map(this.formatNumber).join(':')
        }


    }
};
</script>



<style lang="scss" scoped>

.operate-content{
    padding:10px;
}
.tenant-operation-table{
    padding:0 10px;
    .viewDetail{
        color:#409EFF;
        cursor: pointer;
        &.disabled{
            color: #ccc;
        }
    }
}
.el-pagination{
    text-align:right;
    padding: 15px 20px;
}

.disabledCheckbox{
    .el-table{
        .el-table__header-wrapper{
            .el-checkbox{
                display: none;
            }
        }
    }
}

</style>

<style lang="scss">

// .tenant-operation-table{
//     .el-table__body, .el-table__footer, .el-table__header{
//         font-size: 12px;
//         .el-table__row td{
//             padding: 5px;
//         }
//     }
//     .el-table th, .el-table tr.header-row{
//         height:37px;
//         background-color: #F5F7FA!important;
//         color:#324558;
//         font-size:12px;
//         th.is-leaf{
//             padding:0;
//         }
//     }
// }


</style>